package gbench.appdemo.mall.erp.site;

import gbench.appdemo.mall.erp.MyERPApp;
import gbench.appdemo.mall.erp.components.*;
import gbench.common.fs.FileSystem;
import gbench.common.tree.LittleTree.IRecord;
import gbench.common.tree.LittleTree.Term;

import static gbench.common.tree.LittleTree.IRecord.REC;
import static gbench.common.tree.LittleTree.Term.FT;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.*;

/**
 * 
 * @author gbench
 *
 */
public class InfoSite implements IInfoSite {

    /**
     * 
     * @param home
     */
    public InfoSite(MyERPApp erpApp, final String home) {
        this.home = home;
        this.erpApp = erpApp;
        type = this.getType(home);
    }

    /**
     * 获取产品主目录
     */
    public String getProductHome(final Integer productId) {

        if (this.type == InfoSiteType.LOCAL_FILE) {
            final var path = Term.FT("$0/product/$1", this.home, productId);
            final var file = new File(path);
            if (!file.exists())
                file.mkdirs();
            return file.getAbsolutePath();
        } else {
            return null;
        }

    }

    /**
     * 
     */
    public String getPriceQuoteHome(Integer priceQuoteId) {
        
        return this.getPriceQuoteHome(erpApp.priceQuoteOf(priceQuoteId));
    }

    /**
     * 
     */
    public String getPriceQuoteHome(final IPriceQuote priceQuote) {

        if (priceQuote == null) {
            return null;
        } else {
            final var owner = priceQuote.getOwner();
            final var product = priceQuote.getProduct();
            if (this.type == InfoSiteType.LOCAL_FILE) { // 文件类型的 infoSite
                final var homepath = Term.FT("$0/pricequote/$1_$2_$3", this.home, owner.getId(), product.getId(),priceQuote.getId());
                final var home = new File(homepath);
                if (!home.exists()) {
                    home.mkdirs();
                    
                    final var src = product.attr("path", "D:/sliced/files/products/valuables/gold.jpg");
                    final var srcfile = new File(src); // 源文件
                    final var ext = FileSystem.extensionpicker(src);// 文件扩展名
                    final var imagefile = new File(FT("$0/index.$1",home,ext));
                    final var indexfile = new File(FT("$0/readme.txt",home));
                    
                    FileSystem.write(indexfile, "utf8", ()->{
                        final var line = new StringBuffer();
                        line.append(FT("name:$0\n",product.getName())); // 书写产品名
                        line.append(FT("unitPrice:$0\n",priceQuote.getUnitPrice())); // 书写产品价格
                        line.append(FT("ratio:$0\n",priceQuote.attrs().get("ratio"))); // 书写产品价格
                        line.append(FT("company:$0\n",priceQuote.getOwner())); // 书写产品价格
                        line.append("\n报价详情\n");
                        priceQuote.attrs().foreach((k,v)->{
                            line.append(FT("\t$0:$1\n",k,v)); // 书写产品价格
                        });
                        return line.toString(); // 文本输出
                    });// 文件书写
                    
                    try {
                        copy(srcfile,imagefile);
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                }
                
                return home.getAbsolutePath().replace("\\", "/"); // 分隔符转义
            } else {
                return null;
            }
        }

    }

    /**
     * 
     */
    public InfoSiteType getType(final String infoSite) {
        final var file = new File(infoSite);
        if (file.exists()) {
            return InfoSiteType.LOCAL_FILE;
        } else {
            return InfoSiteType.UNKNONWN;
        }
    }

    /**
     * 
     * @param product
     * @return
     */
    public IRecord getResources(final IProduct product) {
        final var id = product.getId();

        return REC("id",id);
    }

    /**
     * 
     * @param product
     * @return
     */
    public IRecord getResources(final IPriceQuote priceQuote) {
        final var id = priceQuote.getId();
        final var owner = priceQuote.getOwner();
        if (id == null || owner == null)
            return null;

        final var pricequoteSite = this.getPriceQuoteHome(priceQuote);
        final var home = new File(pricequoteSite);
        final List<String> files = new LinkedList<String>();
        FileSystem.tranverse(home, e -> {
            files.add(e.getAbsolutePath());
        });

        return REC("files", files);
    }

    /**
     * 
     * @param product
     * @return
     */
    public IRecord getPriceQuoteResources(final Integer priceQuoteId) {
        return this.getResources(erpApp.priceQuoteOf(priceQuoteId));
    }
    
    /**
     * 
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copy(final File source, final File dest) throws IOException {

        try (final FileChannel inputChannel = new FileInputStream(source).getChannel();
             final FileChannel outputChannel = new FileOutputStream(dest).getChannel()) {
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); // 文件传输
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public final InfoSiteType type;
    public final String home;
    public final MyERPApp erpApp;

}
